<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import * as echarts from 'echarts'
import dashboardApi from '@/api/dashboard.js'
import chinaMap from '@/assets/json/china.json'

const chart = ref(null)
const chartData = ref([])
const loading = ref(false)

// 省份名称映射 - 将后端返回的简化名称转换为地图JSON中的完整名称
const provinceNameMap = {
  '北京': '北京市',
  '天津': '天津市',
  '河北': '河北省',
  '山西': '山西省',
  '内蒙古': '内蒙古自治区',
  '辽宁': '辽宁省',
  '吉林': '吉林省',
  '黑龙江': '黑龙江省',
  '上海': '上海市',
  '江苏': '江苏省',
  '浙江': '浙江省',
  '安徽': '安徽省',
  '福建': '福建省',
  '江西': '江西省',
  '山东': '山东省',
  '河南': '河南省',
  '湖北': '湖北省',
  '湖南': '湖南省',
  '广东': '广东省',
  '广西': '广西壮族自治区',
  '海南': '海南省',
  '重庆': '重庆市',
  '四川': '四川省',
  '贵州': '贵州省',
  '云南': '云南省',
  '西藏': '西藏自治区',
  '陕西': '陕西省',
  '甘肃': '甘肃省',
  '青海': '青海省',
  '宁夏': '宁夏回族自治区',
  '新疆': '新疆维吾尔自治区',
  '台湾': '台湾省',
  '香港': '香港特别行政区',
  '澳门': '澳门特别行政区'
}

// 获取数据并初始化图表
const initChart = async () => {
  try {
    loading.value = true
    
    // 如果已有图表实例，先清理
    if (window.mapChartInstance) {
      window.mapChartInstance.dispose()
      window.mapChartInstance = null
    }

    // 清空容器
    if (chart.value) {
      chart.value.innerHTML = ''
    }

    // 调用后端API获取地图数据
    const response = await dashboardApi.getMap()
    
    if (response.code === 200 && response.data) {
      // 转换数据格式以匹配ECharts地图
      // 后端MapVO只返回 province 和 total 字段
      chartData.value = response.data.map(item => ({
        name: provinceNameMap[item.province] || item.province || '未知',
        value: item.total || 0
      }))
      
      console.log('转换后的地图数据:', chartData.value)
    } else {
      console.warn('获取地图数据失败:', response.message)
      // 使用空数据
      chartData.value = []
    }

    const myChart = echarts.init(chart.value, null, {
      renderer: 'svg',
      width: 'auto',
      height: 'auto'
    })

    // 保存实例到全局变量
    window.mapChartInstance = myChart

    echarts.registerMap('china', chinaMap)

    // 计算数据范围用于颜色映射
    const values = chartData.value.map(item => item.value)
    const maxValue = Math.max(...values, 1)
    const minValue = Math.min(...values, 0)

    const option = {
      animation: false,
      title: {
        text: '全国DNS递归服务器安全态势',
        left: 'center',
        top: '10px',
        textStyle: {
          color: 'white',
          fontSize: 16,
          fontWeight: 600
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          const data = params.data || {}
          return `
            <div style="padding: 8px;">
              <div style="font-weight: bold; margin-bottom: 4px;">${params.name}</div>
              <div>服务器总数: ${data.value || 0}台</div>
            </div>
          `
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1,
        textStyle: {
          color: 'white'
        }
      },
      geo: {
        map: 'china',
        center: [104, 37.5],
        layoutCenter: ['50%', '55%'],
        layoutSize: '85%',
        aspectScale: 0.8,
        left: 0,
        right: 0,
        top: 30,
        bottom: 30,
        itemStyle: {
          areaColor: 'rgba(255, 255, 255, 0.1)',
          borderColor: 'rgba(255, 255, 255, 0.3)',
          borderWidth: 1
        },
        emphasis: {
          itemStyle: {
            areaColor: 'rgba(76, 201, 240, 0.3)',
            borderColor: '#4cc9f0'
          }
        }
      },
      grid: {
        containLabel: false,
        left: 0,
        right: 0,
        bottom: 30,
        top: 30
      },
      visualMap: {
        min: minValue,
        max: maxValue,
        text: ['高', '低'],
        realtime: false,
        calculable: true,
        right: 10,
        bottom: 20,
        itemWidth: 15,
        itemHeight: 100,
        textGap: 8,
        inRange: {
          color: ['rgba(76, 201, 240, 0.3)', 'rgba(76, 201, 240, 0.6)', '#4cc9f0']
        },
        textStyle: {
          color: 'white',
          fontSize: 10
        },
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1
      },
      toolbox: {
        show: true,
        orient: 'horizontal',
        itemSize: 14,
        itemGap: 8,
        showTitle: true,
        top: '10px',
        right: '10px',
        iconStyle: {
          borderColor: 'white'
        },
        emphasis: {
          iconStyle: {
            borderColor: '#4cc9f0'
          }
        },
        feature: {
          saveAsImage: {
            show: true,
            type: 'png',
            name: 'china-map',
            backgroundColor: 'transparent'
          },
          dataView: {
            show: true,
            readOnly: false,
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            textColor: 'white'
          }
        }
      },
      series: [
        {
          name: 'DNS服务器数量',
          type: 'map',
          map: 'china',
          roam: true, // 允许缩放和平移
          center: [104, 37.5],
          layoutCenter: ['50%', '55%'],
          layoutSize: '85%',
          aspectScale: 0.8,
          left: 0,
          right: 0,
          top: 30,
          bottom: 30,
          animation: false,
          progressive: 0,
          emphasis: {
            label: {
              show: true
            }
          },
          data: chartData.value,
          itemStyle: {
            areaColor: 'rgba(255, 255, 255, 0.1)',
            borderColor: 'rgba(255, 255, 255, 0.3)',
            borderWidth: 1
          },
          emphasis: {
            itemStyle: {
              areaColor: 'rgba(76, 201, 240, 0.5)',
              borderColor: '#4cc9f0',
              borderWidth: 2
            },
            label: {
              show: true,
              color: 'white',
              fontSize: 12,
              fontWeight: 'bold'
            }
          }
        }
      ]
    }

    myChart.setOption(option)

    // 响应式处理
    const handleResize = () => {
      if (myChart && !myChart.isDisposed()) {
        myChart.resize()
      }
    }

    window.addEventListener('resize', handleResize)
    
    // 清理函数
    const cleanup = () => {
      window.removeEventListener('resize', handleResize)
      if (myChart && !myChart.isDisposed()) {
        myChart.dispose()
      }
    }

    // 保存清理函数到组件实例
    chart.value._cleanup = cleanup

  } catch (error) {
    console.error('初始化地图失败:', error)
    
    // 如果是401错误，不显示错误消息，让响应拦截器处理跳转
    if (error.code === 401) {
      console.log('Token过期，响应拦截器将处理跳转')
      return
    }
    
    chartData.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  initChart()
})

// 组件卸载时清理
onUnmounted(() => {
  if (chart.value && chart.value._cleanup) {
    chart.value._cleanup()
  }
  if (window.mapChartInstance) {
    window.mapChartInstance.dispose()
    window.mapChartInstance = null
  }
})
</script>

<template>
  <div ref="chart" class="modern-china-map"></div>
</template>

<style scoped>
.modern-china-map {
  width: 100%;
  height: 100%;
  position: relative;
  background: transparent;
  min-height: 300px;
  overflow: hidden;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}

/* ECharts 深度样式覆盖 */
:deep(.echarts-for-react) {
  background: transparent !important;
}

/* 修复ECharts残影问题 */
:deep(canvas) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  opacity: 1;
  transition: none !important;
}

:deep(svg) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  overflow: hidden;
  opacity: 1;
  transition: none !important;
}

/* 强制清除之前的渲染状态 */
:deep(div) {
  background: transparent !important;
  transform: none !important;
}
</style>